package svc

import (
	"context"
	_ "github.com/glebarez/go-sqlite"
	"github.com/zeromicro/go-zero/core/logx"
	"github.com/zeromicro/go-zero/core/stores/sqlx"
	"yunzhan/alert-server/internal/config"
	"yunzhan/alert-server/internal/model"
)

type ServiceContext struct {
	Config             config.Config
	NotificationModel  model.NotificationModel
	AlertRuleModel     model.AlertRuleModel
	Conn               sqlx.SqlConn
	ComponentInfoModel *model.ComponentInfoModel
}

func NewServiceContext(c config.Config) *ServiceContext {

	var dbConn sqlx.SqlConn
	var dbType string
	var notificationsTable, alertRulesTable, componentInfoTable string

	if c.UseMysql {
		dbConn = sqlx.NewMysql(c.Mysql.DataSource)
		dbType = "mysql"
		notificationsTable = c.Mysql.Tables.Notifications
		alertRulesTable = c.Mysql.Tables.AlertRulesInfo
		componentInfoTable = c.Mysql.Tables.ComponentInfo
	} else {
		dbConn = sqlx.NewSqlConn("sqlite", c.SQLite.DataSource)
		dbType = "sqlite"
		notificationsTable = c.SQLite.Tables.Notifications
		alertRulesTable = c.SQLite.Tables.AlertRulesInfo
		componentInfoTable = c.SQLite.Tables.ComponentInfo
	}

	err := model.CreateTables(dbConn, dbType)
	if err != nil {
		logx.Errorf("告警模块元数据表初始化异常: %s", err.Error())
		return nil
	}
	return &ServiceContext{
		Config:             c,
		NotificationModel:  model.NewNotificationModel(context.Background(), notificationsTable, dbConn),
		AlertRuleModel:     model.NewAlertRuleModel(dbConn, alertRulesTable),
		Conn:               dbConn,
		ComponentInfoModel: model.NewComponentInfoModel(dbConn, componentInfoTable),
	}
}
